LeetCode JS Easy 2704. To Be Or Not To Be


Posted by Lucy on 2023-06-10

這是30 Days of JavaScript中的題型
Write a function expect that helps developers test their code. It should take in any value val and return an object with the following two functions.

toBe(val) accepts another value and returns true if the two values === each other. If they are not equal, it should throw an error "Not Equal".
notToBe(val) accepts another value and returns true if the two values !== each other. If they are equal, it should throw an error "Equal".
最常見寫法應該就兩個function

var expect = function(val) {
    const toBe=(eqalVal)=>{if(val===eqalVal)return true
                throw new Error("Not Equal")
    }    
    const notToBe=(eqalVal)=>{if(val!==eqalVal)return true
                throw new Error("Equal")
    }
      return {
          toBe:toBe,
          notToBe:notToBe,
      }
};

不過不知道為什麼我就很想寫共用function,下面這段是第一次寫的

var expect = function(val) {
    const fn=(eqalVal,isToBe)=>{
            const isEqal=val===eqalVal
            if(isToBe){
                if(isEqal)return true
                throw new Error("Not Equal")
            }else{
                if(isEqal)throw new Error("Equal")
                return true
            }
        }
      return {
          toBe:(eqalVal)=>fn(eqalVal,true),
          notToBe:(eqalVal)=>fn(eqalVal,false),
      }
};

#leetcode Js







Related Posts

React 入門 3 - Hooks

React 入門 3 - Hooks

Chapter 3 訂立階段目標,架構流程

Chapter 3 訂立階段目標,架構流程

從前端傳資料給後端(GET, POST)、從 PHP 連線到 MySQL 資料庫

從前端傳資料給後端(GET, POST)、從 PHP 連線到 MySQL 資料庫


Comments